//
//  LBDownloader.m
//  LBDownloader
//
//  Created by WuShiHai on 19/6/14.
//  Copyright (c) 2019 Lebbay All rights reserved.
//

#import "LBDownloader.h"

#import <LBFoundation/LBFoundation.h>

#import "LBDownloaderModel.h"
#import "LBDownloaderModel+Util.h"
#import "LBDownloaderConfigurationHeader.h"

@interface LBDownloader ()<LBDownloaderBlockOperationDelegate>

@property (nonatomic, strong) AFURLSessionManager *sessionManager;
@property (nonatomic, strong) NSOperationQueue *downloadQueue;

@end

@implementation LBDownloader

+ (instancetype)manager{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[LBDownloader alloc] init];
    });
    return instance;
}
- (instancetype)init{
    self = [super init];
    if (self){
        _sessionManager = [[AFURLSessionManager alloc] init];
        _downloadQueue = [[NSOperationQueue alloc] init];
        _downloadQueue.maxConcurrentOperationCount = 10;
    }
    return self;
}

- (void)start:(NSString *)url
        unzip:(BOOL)unzip
        cache:(BOOL)cache
     complete:(LBDownloaderCompleteBlock)complete {
    [self start:url
          unzip:unzip
          cache:cache
       progress:^(NSProgress *downloadProgress){}
       complete:complete];
}

- (void)start:(NSString *)url
        unzip:(BOOL)unzip
        cache:(BOOL)cache
     progress:(LBDownloadProgressBlock)progress
     complete:(LBDownloaderCompleteBlock)complete {
    
    if (url.length <= 0) {
        LBBlockSafeRun(complete, NO, nil);
    } else {
        LBDownloaderModel *downloader = [[LBDownloaderModel alloc] init];
        downloader.isUnzip = unzip;
        downloader.url = url;
        
        LBDownloaderWork *work = [[LBDownloaderWork alloc] init];
        work.downloader = downloader;
        
        //开始下载
        LBDownloaderBlockOperation *operation = [[LBDownloaderBlockOperation alloc] init];
        operation.complete = complete;
        operation.downloadProgress = progress;
        operation.work = work;
        operation.delegate = self;
        operation.cacheOnly = cache;
        
        [self.downloadQueue.operations enumerateObjectsUsingBlock:^(__kindof LBDownloaderBlockOperation * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([[operation.work identity] isEqualToString:[obj.work identity]]) {
                [operation addDependency:obj];
            }
        }];
        
        [self.downloadQueue addOperation:operation];
    }
}

#pragma mark - LBDownloaderBlockOperationDelegate
- (void)didOperationCompleteTask:(LBDownloaderBlockOperation *)operation {
    NSLog(@"下载路径: %@", operation.work.downloader.filePath);
    LBBlockSafeRun(operation.complete, operation.isSuccess, operation.work.downloader);
}

@end
